package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;

/*
 * 该线程的任务是与指定的客户端完成HTTP交互
 * http要求一问一答
 * 1.解析请求
 * 2.处理请求
 * 3.发送相应
 * */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1.解析请求
            /*
             * 测试读取请求行()
             * */
            String line = readLine();
            System.out.println("请求行" + line);
//将请求行中的请求方式,抽象路径,协议版本分别解析出来
            String method;
            String url;
            String protocal;

            String[] crs = line.split("\\s");
            method = crs[0];
            url = crs[1];
            protocal = crs[2];

            System.out.println("method:" + method);
            System.out.println("url:" + url);
            System.out.println("protocal" + protocal);


            HashMap<String, String> hm = new HashMap<>();
            //1.2解析消息头
            while (true) {
                line = readLine();
                /*
                 * 结尾有两个(CRFL),读到最后一个(CRFL)时,sb.tostring().trim()只剩空字符串
                 * */
                if (line.isEmpty()) {
                    break;
                }
                System.out.println("消息头:" + line);

            //消息头按照":"进行拆分存入
                String[] split = line.split(": ");
                hm.put(split[0], split[1]);
            }
            System.out.println(hm);


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //一问一答后,与客户端断开连接(http协议要求)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /*将v2版本测试读取一行字符串的操作封装成一个方法*/

    }

    private String readLine() throws IOException {
        //socket不变,流不变
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder sb = new StringBuilder();
        char cur = 'a', pre = 'a';
        //一问一答,采用stringbuilder
        while ((d = in.read()) != -1) {
            cur = (char) d;
            if (cur == 10 && pre == 13) {
                break;
            }
            sb.append(cur);
            pre = cur;
        }
        return sb.toString().trim();
    }
}
